﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using dtSearch.Engine;


namespace DtSearchIndexService
{
    public class DocumentIndexServiceBll
    {
        static IndexJobSettings GetDialogSettings(IndexServiceInfo OIndexServiceInfo)
        {
            string IndexPath = OIndexServiceInfo.IndexPath;// @"E:\Projects\QNet.Portal\UniversityNet\UserDataStorage\DocumentArchives\sbv\ArchiveDoc\Index";
            string whatToIndex = OIndexServiceInfo.whatToIndex+"<+>";// @"E:\Projects\QNet.Portal\UniversityNet\UserDataStorage\DocumentArchives\sbv\ArchiveDoc\Root<+>";
            string tempFolder = "";
            string maxMemToUseMB = "";
            string autoCommitIntervalEdit = "";
            string filenameFilters = "";
            string excludeFilters = "";
            IndexJobSettings settings = new IndexJobSettings();
            settings.IndexPath = IndexPath;
            settings.FoldersToIndex.Add(whatToIndex);
            settings.TempFileDir = tempFolder;
            int.TryParse(maxMemToUseMB, out settings.MaxMemToUseMB);
            int.TryParse(autoCommitIntervalEdit, out settings.AutoCommitIntervalMB);
            settings.IncludeFilters = Server.Tokenize(filenameFilters);
            settings.ExcludeFilters = Server.Tokenize(excludeFilters);
            return settings;
        }


        public static void Execute(IndexServiceInfo OIndexServiceInfo)
        {
            if (string.IsNullOrEmpty(OIndexServiceInfo.IndexPath))
            {
                throw new Exception("IndexPath chưa thiết lập");
            }
            if (string.IsNullOrEmpty(OIndexServiceInfo.whatToIndex))
            {
                throw new Exception("whatToIndex chưa thiết lập");
            }

            IndexJob ij = new IndexJob();

            IndexJobSettings ijSettings = GetDialogSettings(OIndexServiceInfo);
            ijSettings.CopyTo(ij);

            if (ij.IndexPath.Length < 2)
                return;
            ij.ActionAdd = true;
            ij.ActionCreate = true;

            Options opts = new Options();
            opts.BinaryFiles = BinaryFilesSettings.dtsoFilterBinaryUnicode;
            opts.Hyphens = HyphenSettings.dtsoHyphenAsSpace;
            opts.TextFlags = TextFlags.dtsoTfRecognizeDates | TextFlags.dtsoTfRecognizeDatesPresumeDMY;
            opts.FieldFlags = FieldFlags.dtsoFfSkipFilenameField | FieldFlags.dtsoFfOfficeSkipHiddenContent;
            opts.UnicodeFilterMinTextSize = 6;
            opts.UnicodeFilterFlags = UnicodeFilterFlags.dtsoUfAutoWordBreakByCase |
                    UnicodeFilterFlags.dtsoUfAutoWordBreakByLength |
                    UnicodeFilterFlags.dtsoUfOverlapBlocks;
            opts.UnicodeFilterBlockSize = 4194304;
            opts.Save();
            ij.Execute();
        }
    }
}
